package com.zhentao.Jwtfilter;

import cn.hutool.json.JSONUtil;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.zhentao.constants.Constants;
import com.zhentao.pojo.TUser;
import com.zhentao.result.Result;
import com.zhentao.service.TUserService;
import com.zhentao.utils.JwtService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@WebFilter
public class JwtFilter implements Filter {
    @Resource
    private TUserService userService;
    @Resource
    private JwtService jwtService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求头文件
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.isBlank(token)){
            response.setCharacterEncoding("UTF-8");
            chain.doFilter(request,response);
            return;
        }
        String uri = request.getRequestURI();
        if("/user/login".contains(uri)||"/user/logout".contains(uri) || "/user/userdata".contains(uri)){
            response.setCharacterEncoding("UTF-8");
            chain.doFilter(request, response);
            return;
        }
        Map<String, Object> claimsMap = JwtService.getClaimsMap(token);
        if (claimsMap != null) {
            Object obj = claimsMap.get("user");
            LinkedHashMap map = (LinkedHashMap) obj;
            Integer userId = (Integer) map.get("userId");
            TUser user = userService.getById(userId);
            if(user==null){
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println(JSONUtil.toJsonStr(Result.ERROR("系统故障")));
                return;
            }
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, null,user.getAuthorities());
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            //token续期
            new Thread(()->{
                String rememberMe = request.getParameter("rememberMe");
                if(Boolean.parseBoolean(rememberMe)){
                    jwtService.refreshToken(user, Constants.EXPIRE_TIME, TimeUnit.SECONDS);
                }else{
                    jwtService.refreshToken(user, Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
                }
            }).start();
            chain.doFilter(request, response);
        }else {
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSONUtil.toJsonStr(Result.TOKEN_TIME()));
            return;
        }
    }
}
